package com.xin.di.uav.applet.service.impl;

import com.alibaba.excel.EasyExcel;
import com.xin.di.uav.applet.resp.PaymentBillResp;
import com.xin.di.uav.applet.service.ExportService;
import com.xin.di.uav.applet.service.PaymentBillService;
import com.xin.di.uav.mapper.BillMapper;
import jakarta.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class ExportServiceImpl implements ExportService {


    @Value("${download.tmp.dir:/tmp/excel_export_}")
    private String tmpBaseDir;

    @Autowired
    private PaymentBillService paymentBillService;

    @Autowired
    private BillMapper billMapper;

    @Resource(name = "exportPoolExecutor")
    private Executor exportTaskExecutor;

    @Override
    public void export(String orderNo, Date startTime, Date endTime, HttpServletResponse response) {
        // 1. 创建临时目录
        String tempDir = tmpBaseDir + System.currentTimeMillis();
        try {
            Files.createDirectories(Paths.get(tempDir));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int total = billMapper.count(orderNo, startTime, endTime);
        int pageSize = 10000;
        int totalPages = total / pageSize + 1;
        // 2. 分页并行导出
        List<CompletableFuture<List<PaymentBillResp.Record>>> futures = IntStream.range(0, totalPages).mapToObj(page -> CompletableFuture.supplyAsync(() -> {

            return paymentBillService.list(page * pageSize, pageSize, orderNo, startTime, endTime);
        }, exportTaskExecutor)).toList();

        // 3. 压缩所有文件
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=export.zip");

        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            List<PaymentBillResp.Record> payLogDTOList = new ArrayList<>();
            futures.forEach(future -> {
                try {
                    payLogDTOList.addAll(future.get());
                } catch (InterruptedException | ExecutionException e) {
                    throw new RuntimeException(e);
                }
            });
            String fileName = tempDir + "/账单列表.xlsx";
            try (FileOutputStream out = new FileOutputStream(fileName)) {
                EasyExcel.write(out, PaymentBillResp.Record.class).sheet("Sheet1").doWrite(payLogDTOList);
                File file = new File(fileName);
                zos.putNextEntry(new ZipEntry(file.getName()));
                Files.copy(file.toPath(), zos);
                zos.closeEntry();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 4. 清理临时文件
            try {
                FileUtils.deleteDirectory(new File(tempDir));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
